package servlet;

import com.alibaba.fastjson.JSONObject;
import po.User;
import utils.JdbcUtil;
import utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *          登  录
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JdbcUtil jdbc = new JdbcUtil();
        //获取姓名、密码
        String name = req.getParameter("username");
        String paw = req.getParameter("password");

        HttpSession session = req.getSession();

        //校验 数据库连接
        Connection connection = jdbc.getConnection();
        String sql = "select * from user_1 where name=? and password=?";

        try {
            PreparedStatement pre = connection.prepareStatement(sql);
            pre.setString(1,name);
            pre.setString(2,paw);
            ResultSet res = pre.executeQuery();
            PrintWriter writer = resp.getWriter();


            while (res.next()){
                User user = new User();
                //user获取到传入的信息
                user.setName(res.getString("name"));
                user.setPassword(res.getString("password"));
                //session存储登录信息
                session.setAttribute("userKey",user);

                ResultData success = ResultData.success();
                Object o = JSONObject.toJSON(success);
                writer.println(o.toString());

                jdbc.close(res,pre,connection);
                return;
            }

            ResultData resultData = ResultData.buildMsg(1, "账号名或密码有误");
            Object o = JSONObject.toJSON(resultData);
            writer.println(o.toString());


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
